package com.hean.activity;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemLongClickListener;

import com.hean.entity.Entity;

public class Phone extends Activity {
	private ListView lv;
	private Button addButton;
	private List<Map<String, Object>> contactList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.phone);
		lv = (ListView) findViewById(R.id.phone);
		addButton=(Button)findViewById(R.id.phone_add);
		
		contactList = loadContacts();
		
//		contactList = new ArrayList<Map<String, Object>>();
//		contactList.add(Entity.newContact("steven", "13683395890"));
//		contactList.add(Entity.newContact("outman", "13683395890"));
//		contactList.add(Entity.newContact("memory", "13683395890"));
		// contactList.add(new Contact("steven", "13683395890").toMap());

		ListAdapter adapter = new SimpleAdapter(Phone.this, contactList,
				R.layout.phone_lv, new String[] { "name", "phone" },
				new int[] { R.id.phone_lv_name, R.id.phone_lv_phone });

		lv.setAdapter(adapter);

		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// "android.intent.action.CALL"
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
						+ contactList.get(position).get("phone")));
				startActivity(intent);
				return false;
			}
		});
		addButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Phone.this, AddContact.class);
				startActivity(intent);
			}
			
		});
	}
	
	private List<Map<String, Object>> loadContacts() {
		String path = "/mnt/sdcard/contacts.txt";
		try {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(path), "utf-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				String[] data = line.split(",");
				Map contact = Entity.newContact(data[0], data[1]);
				list.add(contact);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
